from dao.DAOQuanLyNhanVien import DaoQuanLyNhanVien
from google.appengine.api import users
from utils.Const import Const
from utils.permission_required import permission_required
from webapp2_extras.appengine.users import login_required
import WSGI
import json as simplejson
import logging
import webapp2

logger = logging.getLogger("GUIPhanQuyen")

class GuiPhanQuyen(webapp2.RequestHandler):
    
    priv = ''
    perm = 'QuanLy.PhanQuyen'
    @permission_required
    def get(self):
        #DaoQuanLyNhanVien.addAllPrivForManager()
        lstNV, _ = DaoQuanLyNhanVien.getListNhanVien('', '', 1000, 0, '')
        
        for item in lstNV:
            item['tenNV'] = str(item['id']) + ' - ' + item['tenNV']  
        
        lstLoaiNV = DaoQuanLyNhanVien.getListLoaiNhanVien()
        
        lnvAllowedFunc, lnvDeniedFunc = [], []
        if lstLoaiNV != {}:
            lnvAllowedFunc, lnvDeniedFunc = DaoQuanLyNhanVien.getStaffFunctions(lstLoaiNV[0]['id'], Const.LOAI_NV)
            
        nvAllowedFunc, nvDeniedFunc = [], []
        if lstNV != {}:
            nvAllowedFunc, nvDeniedFunc = DaoQuanLyNhanVien.getStaffFunctions(lstNV[0]['id'], Const.NV)
        
        nv = DaoQuanLyNhanVien.getNhanVienByUsername(users.get_current_user().nickname())
        lstPerm = DaoQuanLyNhanVien.getListStaffPriviledge(nv.key().id())
        lstMenu = []
        lstNewPerm = []
        for perm in lstPerm:
            lstMenu.append(perm[:perm.index('.')])
            lstNewPerm.append(perm.replace('.', '-'))
        lstMenu = list(set(lstMenu))
        
        template_values = {
                        'lstPerm': lstNewPerm,
                        'lstMenu': lstMenu,
                        'lstNV': lstNV,
                        'lstLoaiNV':lstLoaiNV,
                        'lnvAllowedFunc':lnvAllowedFunc,
                        'lnvDeniedFunc':lnvDeniedFunc,
                        'nvAllowedFunc':nvAllowedFunc,
                        'nvDeniedFunc':nvDeniedFunc,
                        'nickname': users.get_current_user().nickname(),
                        'signOutUrl': users.create_logout_url(self.request.uri)
        }

        template = WSGI.jinja_environment.get_template('/html/PhanQuyen.html')
        self.response.out.write(template.render(template_values))


class JsonRequestHandler(webapp2.RequestHandler):
    priv = ''
    perm = 'QuanLy.PhanQuyen'
    @permission_required
    def get(self):
        funcName = self.request.get('func')
        funcMapping = {'getQuyen': 'getQuyen',
                       'addQuyen': 'addQuyen',
                       'removeQuyen': 'removeQuyen'}
        func = getattr(self, funcMapping[funcName]);
        result = func();
        self.response.out.write(result)
    
    def post(self):
        return self.get()
    
    def getQuyen(self):
        ma = int(self.request.get('ma'))
        typeId = int(self.request.get('type'))
        lstAllowedFunc, lstDeniedFunc = DaoQuanLyNhanVien.getStaffFunctions(ma, typeId)
        resp = {'lstAllowedFunc':lstAllowedFunc, 'lstDeniedFunc': lstDeniedFunc}
        return simplejson.dumps(resp)
    
    def addQuyen(self):
        ma = int(self.request.get('ma'))
        typeId = int(self.request.get('type'))
        perm = self.request.get('perm')
        func = perm[:perm.rfind('.')]
        priv = perm[perm.rfind('.')+1:]
        pq = DaoQuanLyNhanVien.getPhanQuyen(ma, typeId, func)
        pq.priv = priv
        pq.put()
        return 1
    
    def removeQuyen(self):
        ma = int(self.request.get('ma'))
        typeId = int(self.request.get('type'))
        perm = self.request.get('perm')
        func = perm[:perm.rfind('.')]
        pq = DaoQuanLyNhanVien.getPhanQuyen(ma, typeId, func)
        pq.delete()
        return 1
        
        
            
        